//
//  YH_DomainNameViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/25.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_DomainNameViewController.h"
#import "DomainNameTableViewCell.h"

#import "ModelChoiceButton.h"
//获取数据类
#import "PagingData.h"
#import "GetPagingDataList.h"
//detail
#import "DomainRenewalViewController.h"

//#import "TipView.h"

@interface YH_DomainNameViewController ()<UITableViewDelegate,UITableViewDataSource,PagingDataListServiceDelegate,ASIHTTPRequestDelegate>{
    
    __weak IBOutlet UITableView *_tableView;
    
    GetPagingDataList *DataService;
    //Tipview
    //TipView *tip;
    //网址lbl
    __weak IBOutlet UILabel *webName;
    __weak IBOutlet UITextField *bandingName;
    
    __weak IBOutlet UIView *tipView;
    
    __weak IBOutlet UIView *backView;
    
    NSInteger selectRow;
    
    MBProgressHUD *postHud;
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    ASIFormDataRequest *_request;
}

@end

@implementation YH_DomainNameViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取数据
    [self getDate];
    // 集成刷新控件
    [self setupRefresh];
    [_tableView headerBeginRefreshing];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //标题
    self.navigationItem.title = @"域名管理";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    //uitablerView
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.rowHeight = 72;
    
    //Tipview
    tipView.layer.cornerRadius = 5.0;
    backView.layer.cornerRadius = 5.0;
    tipView.hidden = YES;
//    tip = [[TipView alloc]initWithTitle:@"绑定操作" descriobe:@"域名:" introduce:@"绑定网址" rect:(CGRectMake(20.0, 109.0, 280.0, 200.0))];
//    tip.hidden = NO;
//    [self.view addSubview:tip];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark CustomMethod

-(void)back{
    [_request cancel];
    DataService = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UITableView Method

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (DataService.pageInfo.dataArr.count != 0) {
        return DataService.pageInfo.dataArr.count;
    }else{
        return 0;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"DomainNameCell";
    DomainNameTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = (DomainNameTableViewCell *)[[NSBundle mainBundle]loadNibNamed:@"DomainNameCell" owner:nil options:nil][0];
    }
    NSInteger row = indexPath.row;
    UIImageView *img =(UIImageView *)[cell.contentView viewWithTag:1];
    img.image = [UIImage imageNamed:@"u12.png"];
    
    UILabel *domain = (UILabel *)[cell.contentView viewWithTag:2];
    domain.text = DataService.pageInfo.dataArr[row][@"domain"];
    UILabel *date = (UILabel *)[cell.contentView viewWithTag:3];
    //过期时间
    NSString *str = [DataService.pageInfo.dataArr[row][@"time"] substringToIndex:9];
    
    date.text = [NSString stringWithFormat:@"%@过期",str];
    ModelChoiceButton *renewal = (ModelChoiceButton *)[cell.contentView viewWithTag:4];
    //续费
    [renewal addTarget:self action:@selector(renwal:) forControlEvents:UIControlEventTouchUpInside];
    renewal.index = indexPath;
    //绑定
    ModelChoiceButton *banding = (ModelChoiceButton *)[cell.contentView viewWithTag:5];
    [banding addTarget:self action:@selector(banding:) forControlEvents:UIControlEventTouchUpInside];
    
    banding.index = indexPath;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//获取数据
-(void)getDate{
    DataService = [[GetPagingDataList alloc]initWithAction:@"Domainorderlist" Kind:@"cid"];
    //linkarr = linkService.pageInfo.dataArr;
    DataService.delegate = self;
    
}

#pragma mark IBAction Methods

//进入续费
-(void)renwal:(id)sender{
    ModelChoiceButton *btn = sender;
    selectRow = btn.index.row;
    NSLog(@"%i",selectRow);
    DomainRenewalViewController *DRVC = [[DomainRenewalViewController alloc]initWithNibName:@"DomainRenewalViewController" bundle:nil];
    DRVC.domainName = DataService.pageInfo.dataArr[selectRow][@"domain"];
    DRVC.overdueTime = DataService.pageInfo.dataArr[selectRow][@"time"];
    DRVC.Id = DataService.pageInfo.dataArr[selectRow][@"id"];
    [self.navigationController pushViewController:DRVC animated:YES];
}
//绑定
-(void)banding:(id)sender{
    ModelChoiceButton *btn = sender;
    selectRow = btn.index.row;
    webName.text = DataService.pageInfo.dataArr[selectRow][@"domain"];
    tipView.hidden = NO;
    NSLog(@"%i",selectRow);
}

#pragma mark 刷新

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (DataService.isQuery ||![Constants isExistenceNetwork]) {
        [_tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    DataService.pageInfo.pageno = @"1";
    [DataService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    //    NSLog(@"%i",linkService.isQuery);
    //    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (DataService.isQuery || !DataService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        DataService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [DataService.pageInfo nextPage];
    [DataService pageQuery];
}
#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}
- (void)didRecieveMsg{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
    [_tableView reloadData];
}

#pragma mark TipDelegate Method

- (IBAction)cancel:(id)sender {
    tipView.hidden = YES;
}
//提交
- (IBAction)comfire:(id)sender {
    bandingName.text = @"";
    [self postRequest];
    tipView.hidden = YES;
}

//提交请求
-(void)postRequest{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在绑定，请稍后...";
        }
        
        _request = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        _request.requestMethod = @"POST";
        // 设置超时时间
        _request.timeOutSeconds = 60;
        _request.delegate = self;
        // 设置参数
        action = @"bangding";
        paramsDict = [NSMutableDictionary dictionary];
        paramsDict = @{@"id":DataService.pageInfo.dataArr[selectRow][@"id"],@"Domain":DataService.pageInfo.dataArr[selectRow][@"domain"],@"URL":bandingName.text};//uid会员名;tname:类别名称
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        _request.postBody = [paramsData mutableCopy];
        
        [_request startAsynchronous];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        
        if (errorCode == 0) {
            postHud.hidden = YES;
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
        
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}


-(void)dealloc{
    [_request cancel];
    DataService = nil;
    postHud = nil;
    
}
@end
